package com.wujiale.javacore.stream;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class CreatingStreams {
    // show elements of stream
    public static <T> void show(String title, Stream<T> stream){
        final int SIZE = 10;
        // make stream has at most ten elements
        List<T> firstElements = stream
                .limit(SIZE+1)
                .collect(Collectors.toList());
        System.out.println(title+":");

        for (int i = 0;i < firstElements.size();i++){
            if (i>0) System.out.println(",");
            if (i<SIZE) System.out.println(firstElements.get(i));
            else System.out.println("...");
        }
        System.out.println();
    }
    public static void main(String[] args) throws IOException {
        File file = new File("");
        String canonicalPath = file.getCanonicalPath();
        Path path = Paths.get(canonicalPath + "/src/main/resources/stream/alice30.txt");
        var contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        // stream create functions test
        Stream<String> words = Stream.of(contents.split(","));
        show("words", words);

        Stream<String> song = Stream.of("gently", "down", "the", "stream");
        show("song" ,song);

        Stream<String> empty = Stream.empty();
        show("empty", empty);

        Stream<String> echos = Stream.generate(() -> "Echo");
        show("echos", echos);

        Stream<Double> randoms = Stream.generate(Math::random);
        show("randoms", randoms);

        Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
        show("integers", integers);

        try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)){
            show("lines", lines);
        }

        Iterable<Path> iterable = FileSystems.getDefault().getRootDirectories();
        Stream<Path> rootDirectories = StreamSupport.stream(iterable.spliterator(), false);
        show("rootDirectories", rootDirectories);
    }
}
